package com.txw.vod.service.impl;

import com.aliyun.vod.upload.UploadVideo;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadAttachedMediaRequest;
import com.aliyun.vod.upload.req.UploadFileStreamRequest;
import com.aliyun.vod.upload.resp.UploadFileStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.txw.sercicebase.exceptionhandller.LingqiException;
import com.txw.vod.Utils.ConstanVodUtils;
import com.txw.vod.Utils.InitObject;
import com.txw.vod.service.VodService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

@Service
public class VodServiceImp implements VodService {


    /**
     * 删除多个阿里云视频
     *
     * @param videoIdList
     */
    @Override
    public void removeMoreAlyVideo(List<String> videoIdList) {
        try {
            //初始化对象
            DefaultAcsClient client = InitObject.initVodClient(ConstanVodUtils.ACCESS_KEY_ID, ConstanVodUtils.ACCESS_KEY_SECRET);
            //创建一个删除视频的request对象
            DeleteVideoRequest request = new DeleteVideoRequest();

            String video = StringUtils.join(videoIdList.toArray(), ",");
            //  向request设置视频id
            request.setVideoIds(video);
            //调用初始化对象实的方法现删除
            client.getAcsResponse(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LingqiException(20001, "删除失败");
        }
    }

    /**
     * 上传视频到阿里云
     *
     * @param file
     * @return
     */
    @Override
    public String uploadVideoAly(MultipartFile file) {
        try {
            //上传文件名
            String fileName = file.getOriginalFilename();
            //上传后显示的文件名
            String title = fileName.substring(0, fileName.lastIndexOf("."));

            InputStream inputStream = file.getInputStream();
            UploadFileStreamRequest request = new UploadFileStreamRequest(ConstanVodUtils.ACCESS_KEY_ID, ConstanVodUtils.ACCESS_KEY_SECRET, title, fileName);
            System.out.println(ConstanVodUtils.ACCESS_KEY_ID);

            UploadVideo uploadVideo = new UploadVideoImpl();
            UploadFileStreamResponse response = uploadVideo.uploadFileStream(request);
            String videoId = null;
            if (response.isSuccess()) {
                videoId = response.getVideoId();
            } else {
                videoId = response.getVideoId();
            }
            return videoId;
        } catch (Exception e) {

            e.printStackTrace();
            return null;
        }

    }
}
